package com.gitee.zeric.codec.generaters;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.gitee.zeric.codec.exception.ParamErrorException;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zj
 * @date 2021/12/13
 * 日期时间生成器
 */
@Slf4j
public class DateTimeGenerater extends AbstractCodeGerator {

    @Override
    public String generate(String ruleCode, JSONObject param) {
        String format = param.getString("format");
        if(StrUtil.equals(format,"syy")){
            //取后年份前两位
            return DateTime.now().toString("yyyy").substring(0,2);
        }
        if(StrUtil.equals(format,"pyy")){
            //取后年份后两位
            return DateTime.now().toString("yyyy").substring(2);
        }
        return DateTime.now().toString(format);
    }


    @Override
    protected String[] fields() {
        return new String[]{"format"};
    }

    @Override
    public void checkParam(JSONObject paramJson) {
        super.checkParam(paramJson);
        RuleParam param = trans(RuleParam.class, paramJson);
//        try {
            String format = param.getFormat();
            if(StrUtil.isBlank(format)){
                throw new ParamErrorException("请检查格式化字符正确性！");
            }
//            DateTime.now().toString(format);
//        } catch (Exception e) {
//            throw new ParamErrorException("请检查格式化字符正确性！");
//        }
    }

    @Override
    public int size(JSONObject paramJson) {
        if(paramJson!=null && paramJson.containsKey("format")){
            return paramJson.getString("format").length();
        }
        return 0;
    }
}
